<?php

class SiteController extends Controller
{
    private $_identity;
    public $rememberMe;

    public function actionIndex()
    {
        $widgets = $this->connection->createCommand("select * from crm_widget ORDER BY seq asc")
            ->queryAll();

        $widgets_first = Array();
        $widgets_second = Array();
        $widgets_third = Array();

        $i=0;
        foreach ($widgets as $widget){
            if($i%3==0){
                $widgets_first[] = $widget;
            }else if($i%3==1){
                $widgets_second[] = $widget;
            }else if($i%3==2){
                $widgets_third[] = $widget;
            }
            $i++;
        }

        $this->render('index',Array('widgets_first'=>$widgets_first,'widgets_second'=>$widgets_second,'widgets_third'=>$widgets_third));
    }

    public function actionWelcome()
    {
        $this->render('welcome');
    }

    public function actionHome()
    {
        $this->render("home");
    }

    public function actionLoginout()
    {

        $user_id = Yii::app()->user->user_id;
        $message = Yii::app()->user->realname . "，退出系统";
        //登入成功，记录登入历史
        $this->connection->createCommand("insert into crm_loginhistory (user_id,message) values (:user_id,:message)")
            ->bindParam(':user_id', $user_id, PDO::PARAM_INT)
            ->bindParam(':message', $message, PDO::PARAM_STR)
            ->execute();

        Yii::app()->user->logout();
        $this->redirect("/index.html");

//        $this->redirect(Yii::app()->homeUrl);
//        unset(Yii::app()->session['user']);
//        $this->redirect("/index.html");
    }

    public function actionLogin()
    {
        $username = $_REQUEST['username'];
        $password = $_REQUEST['password'];

        $this->_identity = new UserIdentity($username, $password);
        $this->_identity->authenticate();
        if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
            $duration = $this->rememberMe ? 3600 * 24 * 30 : 0; // 30 days
            Yii::app()->user->login($this->_identity, $duration);

            $user_id = Yii::app()->user->user_id;
            $message = Yii::app()->user->realname . "，登入系统";
            //登入成功，记录登入历史
            $this->connection->createCommand("insert into crm_loginhistory (user_id,message) values (:user_id,:message)")
                ->bindParam(':user_id', $user_id, PDO::PARAM_INT)
                ->bindParam(':message', $message, PDO::PARAM_STR)
                ->execute();

            echo json_encode(Appcode::success);
        } else if ($this->_identity->errorCode === UserIdentity::ERROR_USERNAME_INVALID) {
            echo json_encode(Appcode::error_username);
        } else {
            echo json_encode(Appcode::error_password);
        }
    }

    /**
     * 用户个人设置界面
     */
    public function actionConfig()
    {
        if (Yii::app()->user->checkAccess('personalconfig_config')) {
            $user_id = Yii::app()->user->user_id;
            $userinfo = $this->connection->createCommand("select * from crm_user where user_id = :user_id")->bindParam(':user_id', $user_id, PDO::PARAM_INT)
                ->queryRow();

            $this->render("config", ['userinfo' => $userinfo]);
        } else {
            echo json_decode(Appcode::error_noauthority);
        }
    }

    public function actionSaveconfig()
    {
        if (Yii::app()->user->checkAccess('personalconfig_config')) {
            //保存
            $user_id = $_REQUEST['user_id'];
            $userimage = $_REQUEST['userimage'];
            $password = $_REQUEST['password'];

            //修改密码，头像
            $this->connection->createCommand("update crm_user set userimage = :userimage where user_id = :user_id")
                ->bindParam(':user_id', $user_id, PDO::PARAM_INT)
                ->bindParam(':userimage', $userimage, PDO::PARAM_STR)
                ->execute();

            if (!is_null($password) && $password != "") {
                $this->connection->createCommand("update crm_user set password = :password where user_id = :user_id")
                    ->bindParam(':user_id', $user_id, PDO::PARAM_INT)
                    ->bindParam(':password', $password, PDO::PARAM_STR)
                    ->execute();
            }

            echo json_encode(Appcode::success);
        } else {
            echo json_decode(Appcode::error_noauthority);
        }
    }

    private function actionRoletest()
    {
        $auth = Yii::app()->authManager;
        $auth->createOperation('createPost', 'create a post');
        $auth->createOperation('readPost', 'read a post');
        $auth->createOperation('updatePost', 'update a post');
        $auth->createOperation('deletePost', 'delete a post');
        $bizRule = 'return Yii::app()->user->id==$params["post"]->authID;';
        $task = $auth->createTask('updateOwnPost', 'update a post by author himself', $bizRule);
        $task->addChild('updatePost');
        $role = $auth->createRole('reader');
        $role->addChild('readPost');
        $role = $auth->createRole('author');
        $role->addChild('reader');
        $role->addChild('createPost');
        $role->addChild('updateOwnPost');
        $role = $auth->createRole('editor');
        $role->addChild('reader');
        $role->addChild('updatePost');
        $role = $auth->createRole('admin');
        $role->addChild('editor');
        $role->addChild('author');
        $role->addChild('deletePost');
        $auth->assign('reader', 1);
        $auth->assign('author', 1);
        $auth->assign('editor', 1);
        $auth->assign('admin', 1);
    }

    //http://standard.crm.com/y.php?r=site/initcolumns
    public function actionInitcolumns()
    {
        //查询所有的module
        $modules = $this->connection->createCommand("select * from crm_module")->queryAll();
        $this->connection->createCommand("delete from crm_module_column")->execute();
        foreach ($modules as $m) {
            $columns = $this->connection->createCommand("SHOW FULL COLUMNS FROM  " . $m['moduletable'])->queryAll();
            foreach ($columns as $c) {
                if ($c['Field'] != $modules['moduleentityid']) {
                    $this->connection->createCommand("insert into crm_module_column (columnname ,columnlabel ,
columntype ,columndatatype ,display ,ismust,modulename) values (:columnname ,:columnlabel,'basic',:columndatatype,1 ,0,:modulename)")
                        ->bindParam(':columnname', $c['Field'], PDO::PARAM_STR)
                        ->bindParam(':columnlabel', $c['Comment'], PDO::PARAM_STR)
                        ->bindParam(':columndatatype', $c['Type'], PDO::PARAM_STR)
                        ->bindParam(':modulename', $m['moduleenname'], PDO::PARAM_STR)
                        ->execute();
                } else if ($c['Field'] == 'deleted') {
                    $this->connection->createCommand("insert into crm_module_column (columnname ,columnlabel ,
columntype ,columndatatype ,display ,ismust,modulename) values (:columnname ,:columnlabel,'deleted',:columndatatype,1 ,0,:modulename)")
                        ->bindParam(':columnname', $c['Field'], PDO::PARAM_STR)
                        ->bindParam(':columnlabel', $c['Comment'], PDO::PARAM_STR)
                        ->bindParam(':columndatatype', $c['Type'], PDO::PARAM_STR)
                        ->bindParam(':modulename', $m['moduleenname'], PDO::PARAM_STR)
                        ->execute();
                } else if ($c['Field'] == $modules['moduleentityid']) {
                    $this->connection->createCommand("insert into crm_module_column (columnname ,columnlabel ,
columntype ,columndatatype ,display ,ismust,modulename) values (:columnname ,:columnlabel,'primarykey',:columndatatype,1 ,0,:modulename)")
                        ->bindParam(':columnname', $c['Field'], PDO::PARAM_STR)
                        ->bindParam(':columnlabel', $c['Comment'], PDO::PARAM_STR)
                        ->bindParam(':columndatatype', $c['Type'], PDO::PARAM_STR)
                        ->bindParam(':modulename', $m['moduleenname'], PDO::PARAM_STR)
                        ->execute();
                }
            }
        }
    }

    //http://standard.crm.com/y.php?r=site/initmodulecolumnns&module=gathers
    //customer
    public function actionInitmodulecolumnns()
    {
        $module = $_REQUEST['module'];

        if(is_null($module)){
            return;
        }

        $this->connection->createCommand("delete from crm_module_column where modulename = :module")
            ->bindParam(':module', $module, PDO::PARAM_STR)
            ->execute();

        $moduleinfo = $this->connection->createCommand("select * from crm_module where moduleenname = :module")
            ->bindParam(':module', $module, PDO::PARAM_STR)
            ->queryRow();

        $columns = $this->connection->createCommand("SHOW FULL COLUMNS FROM  " . $moduleinfo['moduletable'])->queryAll();
        foreach ($columns as $c) {
            if ($c['Field'] == 'deleted') {
                $this->connection->createCommand("insert into crm_module_column (columnname ,columnlabel ,
columntype ,columndatatype ,display ,ismust,modulename) values (:columnname ,:columnlabel,'deleted',:columndatatype,1 ,0,:modulename)")
                    ->bindParam(':columnname', $c['Field'], PDO::PARAM_STR)
                    ->bindParam(':columnlabel', $c['Comment'], PDO::PARAM_STR)
                    ->bindParam(':columndatatype', $c['Type'], PDO::PARAM_STR)
                    ->bindParam(':modulename', $moduleinfo['moduleenname'], PDO::PARAM_STR)
                    ->execute();
            } else if ($c['Field'] == $moduleinfo['moduleentityid']) {
                $this->connection->createCommand("insert into crm_module_column (columnname ,columnlabel ,
columntype ,columndatatype ,display ,ismust,modulename) values (:columnname ,:columnlabel,'primarykey',:columndatatype,1 ,0,:modulename)")
                    ->bindParam(':columnname', $c['Field'], PDO::PARAM_STR)
                    ->bindParam(':columnlabel', $c['Comment'], PDO::PARAM_STR)
                    ->bindParam(':columndatatype', $c['Type'], PDO::PARAM_STR)
                    ->bindParam(':modulename', $moduleinfo['moduleenname'], PDO::PARAM_STR)
                    ->execute();
            }else if($c['Field']=='createtime'||$c['Field']=='updatetime'){
                $this->connection->createCommand("insert into crm_module_column (columnname ,columnlabel ,
columntype ,columndatatype ,display ,ismust,modulename) values (:columnname ,:columnlabel,'timestamp',:columndatatype,1 ,0,:modulename)")
                    ->bindParam(':columnname', $c['Field'], PDO::PARAM_STR)
                    ->bindParam(':columnlabel', $c['Comment'], PDO::PARAM_STR)
                    ->bindParam(':columndatatype', $c['Type'], PDO::PARAM_STR)
                    ->bindParam(':modulename', $moduleinfo['moduleenname'], PDO::PARAM_STR)
                    ->execute();
            }else if ($c['Field'] != $moduleinfo['moduleentityid']) {
                $this->connection->createCommand("insert into crm_module_column (columnname ,columnlabel ,
columntype ,columndatatype ,display ,ismust,modulename) values (:columnname ,:columnlabel,'basic',:columndatatype,1 ,0,:modulename)")
                    ->bindParam(':columnname', $c['Field'], PDO::PARAM_STR)
                    ->bindParam(':columnlabel', $c['Comment'], PDO::PARAM_STR)
                    ->bindParam(':columndatatype', $c['Type'], PDO::PARAM_STR)
                    ->bindParam(':modulename', $moduleinfo['moduleenname'], PDO::PARAM_STR)
                    ->execute();
            }
        }
    }

}